<?php

namespace tmcore\services\sms\driver;

use tmcore\services\sms\BaseSms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use tmcore\exceptions\MsgException;

/**
 * 阿里云短信服务
 */
class Aliyun extends BaseSms
{
    /**
     * 发送短信
     * @param array $params 参数
     * @return mixed
     * @throws MsgException
     */
    public function sendSms($params) {

        try {
            AlibabaCloud::accessKeyClient($this->smsConfig['accessKeyId'], $this->smsConfig['accessKeySecret'])
                ->regionId('cn-hangzhou')
                ->asDefaultClient();

            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'SignName'      => $this->smsConfig['signName'] ?? '',
                        'PhoneNumbers'  => $this->mobile,
                        'TemplateCode'  => $this->templateCode,
                        'TemplateParam' => $this->getTemplateParam($params),
                    ],
                ])->request();

            $result = $result->toArray();
            if (isset($result['Code']) && $result['Code'] == 'OK') {
                return true;
            }

            throw new MsgException($result['Message'] ?? $result);
        } catch (ClientException | ServerException $e) {
            throw new MsgException($e->getErrorMessage());
        } catch (MsgException $e) {
            throw new MsgException($e->getMessage());
        }
    }
}